package com.boodaba.todocarts.app;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.boodaba.todocarts.domain.ILabelRepository;
import com.boodaba.todocarts.domain.Label;
import com.boodaba.todocarts.domain.Todo;
import com.google.inject.Inject;

public class LabelTodosPresenter extends BasePresenter<ILabelTodosActivity> {
	
	private ILabelRepository mLabelRepository;
	private Label mTargetLabel;

	@Inject
	public LabelTodosPresenter(ILabelRepository labelRepository) {
		mLabelRepository = labelRepository;
	}
	
	public void initializeWith(ILabelTodosActivity activity) {
		super.initializeWith(activity);
		
		mTargetLabel = mLabelRepository.getLabelByTitle(getActivity().getTargetLabelTitle());
		getActivity().setLabelTitle(mTargetLabel.getTitle());
		refresh();
	}

	public void startSettingTodos() {
		getActivity().startSettingTodos(mTargetLabel.getTitle());
	}

	public void processTodo() {
		final String todoTitle = getActivity().getSelectedTodoTitle();
		Todo selectedTodo = mTargetLabel.getTodoByTitle(todoTitle);
		if (selectedTodo == null) {
			return;
		}
		Boolean isCompleted = selectedTodo.isCompleted();
		if (!isCompleted) {
			mTargetLabel.completeTodo(selectedTodo);
		}
		else {
			mTargetLabel.inviteTodo(selectedTodo);
		}
		mLabelRepository.save(mTargetLabel);
		
		if (!isCompleted) {
			getActivity().setTodoMarked(todoTitle);
		}
		else {
			getActivity().setTodoUnmarked(todoTitle);
		}
	}
	
	public void refresh() {
		setTodoTable();
	}
	
	public void returnTo() {
		setTodoTable();
	}
	
	private void setTodoTable()	{
		getActivity().setTodoList(getHashedTodoTitles());
	}
	
	private Map<String, Boolean> getHashedTodoTitles() {
		return buildTodoTitleDictionary(mTargetLabel.getIncompletedTodos());
	}
	
	private Map<String, Boolean> buildTodoTitleDictionary(List<Todo> todos) {
		TreeMap<String, Boolean> titleDict = new TreeMap<String, Boolean>();
		for (Todo todoItem : todos) {
			titleDict.put(todoItem.getTitle(), todoItem.isCompleted());
		}
		return titleDict;
	}
}
